package com.tjetc.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.core.io.Resource;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/images")
public class ImageController {

    @Value("${custom.image.path}")
    private String basePath;

    // 修改后的代码片段
    @GetMapping("/{filename:.+}")
    public ResponseEntity<Resource> getImage(@PathVariable String filename) {
        Path file = Paths.get(basePath).resolve(filename);
        try {
            Resource resource = new UrlResource(file.toUri()); // 直接使用UrlResource
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .contentType(MediaType.IMAGE_JPEG) // 建议动态判断类型
                        .body(resource);
            }
        } catch (Exception e) {
            e.printStackTrace(); // 打印具体错误
        }
        return ResponseEntity.notFound().build();
    }
}
